# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-06 7:08
# File     : logging_examples.py
# Project  : codebuddy_craft
# Desc     : 创建一个日志使用示例文件

# examples/logging_examples.py
"""
日志系统使用示例 📝

展示如何使用日志系统的各种功能
"""

import asyncio
import time
from backend.utils.logger import (
    get_logger,
    get_security_logger,
    get_performance_logger,
    get_business_logger,
    log_execution_time,
    log_async_execution_time
)
from backend.utils.log_utils import (
    log_function_call,
    log_api_request,
    log_security_event,
    log_performance_metric,
    create_log_context,
    create_performance_profiler,
    log_business_event
)


# ============= 基础日志使用 =============

def basic_logging_example():
    """基础日志使用示例 📝"""
    logger = get_logger(__name__)

    logger.debug("🔍 这是一个调试消息")
    logger.info("ℹ️ 这是一个信息消息")
    logger.warning("⚠️ 这是一个警告消息")
    logger.error("❌ 这是一个错误消息")
    logger.critical("🚨 这是一个严重错误消息")


# ============= 装饰器使用示例 =============

@log_execution_time("math_operations")
def calculate_fibonacci(n: int) -> int:
    """计算斐波那契数列 (带执行时间记录)"""
    if n <= 1:
        return n
    return calculate_fibonacci(n - 1) + calculate_fibonacci(n - 2)


@log_async_execution_time("async_operations")
async def async_database_query(query: str) -> dict:
    """模拟异步数据库查询 (带执行时间记录)"""
    await asyncio.sleep(0.1)  # 模拟数据库延迟
    return {"result": f"查询结果: {query}"}


@log_function_call("user_service")
def create_user(username: str, email: str) -> dict:
    """创建用户 (带函数调用记录)"""
    user_data = {
        "id": 12345,
        "username": username,
        "email": email,
        "created_at": time.time()
    }
    return user_data


# ============= 安全日志示例 =============

def security_logging_example():
    """安全日志使用示例 🔒"""

    # 记录认证尝试
    log_security_event(
        "auth_attempt",
        username="john_doe",
        ip_address="192.168.1.100",
        success=True,
        method="password"
    )

    # 记录权限拒绝
    log_security_event(
        "permission_denied",
        user_id="12345",
        resource="/admin/users",
        action="delete",
        reason="insufficient_privileges"
    )

    # 记录可疑活动
    log_security_event(
        "suspicious_activity",
        description="多次失败登录尝试",
        ip_address="203.0.113.1",
        attempts=5,
        time_window="5 minutes"
    )


# ============= 性能监控示例 =============

def performance_logging_example():
    """性能监控使用示例 📊"""
    perf_logger = get_performance_logger("api_performance")

    # 记录各种性能指标
    perf_logger.record_duration("api_response_time", 0.245)
    perf_logger.record_counter("api_requests", 150)
    perf_logger.record_memory_usage("heap_usage", 128.5)
    perf_logger.record_throughput("requests_per_second", 45.2)
    perf_logger.record_latency("database_query", 15.8, "p95")
    perf_logger.record_error_rate("api_errors", 0.02)

    # 使用计时器
    with perf_logger.start_timer("complex_operation"):
        time.sleep(0.1)  # 模拟复杂操作

    # 输出指标汇总
    perf_logger.flush_metrics()


# ============= 业务事件日志示例 =============

def business_logging_example():
    """业务事件日志使用示例 💼"""

    # 记录用户注册
    log_business_event(
        "user_registration",
        user_id="user_123",
        email="john@example.com",
        registration_source="web",
        referrer="google"
    )

    # 记录项目创建
    log_business_event(
        "project_creation",
        user_id="user_123",
        project_id="proj_456",
        project_name="AI Code Assistant",
        project_type="python",
        template="fastapi"
    )

    # 记录文件上传
    log_business_event(
        "file_upload",
        user_id="user_123",
        file_name="main.py",
        file_size=2048,
        file_type="python",
        project_id="proj_456"
    )


# ============= 上下文日志示例 =============

def context_logging_example():
    """上下文日志使用示例 📋"""

    # 使用日志上下文
    with create_log_context("user_operation", user_id="12345", operation="file_upload"):
        logger = get_logger(__name__)
        logger.info("开始处理文件上传")

        time.sleep(0.1)  # 模拟处理时间

        logger.info("文件验证完成")
        logger.info("文件保存完成")


# ============= 性能分析器示例 =============

def performance_profiler_example():
    """性能分析器使用示例 📊"""
    profiler = create_performance_profiler("complex_workflow")

    profiler.start()

    # 第一个阶段
    time.sleep(0.05)
    profiler.checkpoint("data_validation")

    # 第二个阶段
    time.sleep(0.08)
    profiler.checkpoint("data_processing")

    # 第三个阶段
    time.sleep(0.03)
    profiler.checkpoint("data_saving")

    profiler.finish()


# ============= API请求日志示例 =============

def api_logging_example():
    """API请求日志使用示例 🌐"""

    # 记录API请求
    request_info = {
        "method": "POST",
        "path": "/api/users",
        "client_ip": "192.168.1.50",
        "user_agent": "Mozilla/5.0 (Chrome/91.0)",
        "content_type": "application/json",
        "content_length": "256",
        "user_id": "12345"
    }
    log_api_request(request_info)

    # 模拟处理时间
    time.sleep(0.1)

    # 记录API响应
    from backend.utils.log_utils import log_api_response
    response_info = {
        "method": "POST",
        "path": "/api/users",
        "status_code": 201,
        "duration": 0.1,
        "response_size": "128"
    }
    log_api_response(response_info)


# ============= 错误处理日志示例 =============

def error_logging_example():
    """错误处理日志使用示例 ❌"""
    from backend.utils.log_utils import log_error_with_context

    try:
        # 模拟一个错误
        result = 10 / 0
    except Exception as e:
        context = {
            "user_id": "12345",
            "operation": "calculate_percentage",
            "input_data": {"numerator": 10, "denominator": 0},
            "timestamp": time.time()
        }
        log_error_with_context(e, context)


# ============= 运行所有示例 =============

async def run_all_examples():
    """运行所有日志示例 🚀"""
    print("🚀 开始运行日志系统示例...")

    # 基础日志
    print("\n📝 基础日志示例:")
    basic_logging_example()

    # 装
